<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="仓库名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入仓库名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建者" prop="creator">
          <el-input
            v-model="queryParams.creator"
            placeholder="请输入创建者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="仓库类型" clearable style="width: 200px">
            <el-option label="公开" value="PUBLIC" />
            <el-option label="私有" value="PRIVATE" />
            <el-option label="内部" value="INTERNAL" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 仓库表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="repositoryList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="仓库名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="创建者" align="center" prop="creatorName" width="120" />
        <el-table-column label="类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分支数量" align="center" prop="branchCount" width="100" />
        <el-table-column label="提交数量" align="center" prop="commitCount" width="100" />
        <el-table-column label="协作者数量" align="center" prop="collaboratorCount" width="100" />
        <el-table-column label="最后活动" align="center" prop="lastActivityTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastActivityTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              link
            >查看</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              link
            >删除</el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" style="margin-left: 10px">
              <el-button type="primary" link>
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleBranches" icon="Share">分支管理</el-dropdown-item>
                  <el-dropdown-item command="handleCommits" icon="Clock">提交历史</el-dropdown-item>
                  <el-dropdown-item command="handleCollaborators" icon="User">协作者</el-dropdown-item>
                  <el-dropdown-item command="handleIssues" icon="Warning">问题管理</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRepositoryPage, deleteRepository } from '@/api/version'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const repositoryList = ref([])
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  creator: undefined,
  type: undefined
})

// 获取仓库列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getRepositoryPage(queryParams)
    if (response.code === 200) {
      repositoryList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 查看仓库
const handleView = (row) => {
  router.push(`/version/repository/${row.id}/view`)
}

// 删除按钮操作
const handleDelete = (row) => {
  const repositoryIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除仓库编号为"' + repositoryIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRepository(repositoryIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除仓库失败:', error)
      ElMessage.error('删除仓库失败')
    }
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleBranches':
      handleBranches(row)
      break
    case 'handleCommits':
      handleCommits(row)
      break
    case 'handleCollaborators':
      handleCollaborators(row)
      break
    case 'handleIssues':
      handleIssues(row)
      break
    default:
      break
  }
}

// 分支管理
const handleBranches = (row) => {
  router.push(`/version/repository/${row.id}/branches`)
}

// 提交历史
const handleCommits = (row) => {
  router.push(`/version/repository/${row.id}/commits`)
}

// 协作者管理
const handleCollaborators = (row) => {
  router.push(`/version/repository/${row.id}/collaborators`)
}

// 问题管理
const handleIssues = (row) => {
  router.push(`/version/repository/${row.id}/issues`)
}

// 工具函数
const getTypeTag = (type) => {
  const typeMap = {
    'PUBLIC': 'success',
    'PRIVATE': 'danger',
    'INTERNAL': 'warning'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    'PUBLIC': '公开',
    'PRIVATE': '私有',
    'INTERNAL': '内部'
  }
  return textMap[type] || type
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}
</style>
